import { useState, useEffect, useRef, MutableRefObject } from 'react';

type IcallBackEvents = { [key: `on${string}`]: Function };
export function useFormState<T extends Iprops, U extends IcallBackEvents>(
  props: T | (() => T),
  callBackEvents?: U,
  emit?: (type: any, ...arg: any) => void,
): [state: T, setState: React.Dispatch<React.SetStateAction<T>>, events: MutableRefObject<U>] {
  const [state, $state] = useState(props);
  const events = useRef(callBackEvents || ({} as U));
  useEffect(() => {
    emit?.('onComponentDidMount');
    return () => {
      emit?.('onComponentWillUnmount');
    };
  }, []);

  useEffect(() => {
    emit?.('onWatch', state);
  }, [state]);

  return [state, $state, events];
}
